package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.FileAdapter;
import flc.ast.bean.MyFileBean;
import flc.ast.databinding.ActivityLocalFileBinding;
import flc.ast.dialog.AddDialog;
import flc.ast.dialog.AddFolderDialog;
import flc.ast.dialog.AddTextDialog;
import flc.ast.dialog.DeleteDialog;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.dialog.SortDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.MimeUtils;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.UriUtil;

public class LocalFileActivity extends BaseAc<ActivityLocalFileBinding> {

    public static String sPath;
    private List<MyFileBean> mFileBeanList = new ArrayList<>();
    private FileAdapter fileAdapter;
    private String mCurrentRootPath, mSelPath;
    private BasePopupView sortPopup, editPopup, addPopup;
    private SortDialog sortDialog;
    private EditDialog editDialog;
    private AddDialog addDialog;
    private int sortBy;
    private boolean isOrder;


    @Override
    protected int onCreate() {
        return R.layout.activity_local_file;
    }

    @Override
    public void onBackPressed() {
        if (mCurrentRootPath.equals(sPath) || mCurrentRootPath.equals(Environment.getExternalStorageDirectory().getPath())) {
            super.onBackPressed();
        } else {
            mCurrentRootPath = FileUtils.getDirName(mCurrentRootPath);
            mCurrentRootPath = mCurrentRootPath.substring(0, mCurrentRootPath.length() - 1);
            getData(mCurrentRootPath);
        }
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivLocalFileBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.llSortType.setOnClickListener(this);
        mDataBinding.ivSort.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        fileAdapter = new FileAdapter();
        mDataBinding.rvFileList.setAdapter(fileAdapter);
        fileAdapter.addChildClickViewIds(R.id.ivFileDetails);
        fileAdapter.setOnItemClickListener(this);
        fileAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivAdd) {  //添加
            showAddDialog();
        } else if (id == R.id.ivSort) { //排序
            showSortDialog();
        } else if (id == R.id.llSortType) {    //排序顺序
            isOrder = !isOrder;
            mDataBinding.ivSortType.setImageResource(isOrder ? R.drawable.xxjt : R.drawable.xsjt);
            sortFileBeanList();
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        String path = fileAdapter.getItem(position).getPath();
        if (FileUtils.isDir(path)) {
            mCurrentRootPath = path;
            getData(mCurrentRootPath);
        } else if (MimeUtils.isImgMimeType(path)) {
            Uri imageUri = UriUtil.path2Uri(mContext, path);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(imageUri, "image/*");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        } else if (MimeUtils.isVideoMimeType(path)) {
            Uri videoUri = UriUtil.path2Uri(mContext, path);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(videoUri, "video/*");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        } else if (MimeUtils.isAudioMimeType(path)) {
            Uri audioUri = UriUtil.path2Uri(mContext, path);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(audioUri, "audio/*");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        } else {
            gotoPreviewDoc(UriUtil.path2Uri(mContext, path));
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivFileDetails) {
            mSelPath = fileAdapter.getItem(position).getPath();
            showEditDialog(view);
        }
    }

    @Override
    protected void initData() {
        mCurrentRootPath = sPath;
        mDataBinding.tvSortType.setText(getString(R.string.default_sorting));
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData(mCurrentRootPath);
    }

    private void getData(String rootPath) {
        List<File> files = FileUtils.listFilesInDir(rootPath);
        if (files.size() == 0) {
            mDataBinding.ivFileNoData.setVisibility(View.VISIBLE);
            mDataBinding.rvFileList.setVisibility(View.GONE);
        } else {
            mDataBinding.ivFileNoData.setVisibility(View.GONE);
            mDataBinding.rvFileList.setVisibility(View.VISIBLE);
            mFileBeanList.clear();
            for (File file : files) {
                mFileBeanList.add(new MyFileBean(file.getPath(), file.getName(), file.length(),
                        FileUtils.getFileLastModified(file) / 1000L));
            }
            mDataBinding.rvFileList.scrollToPosition(0);
            sortFileBeanList();
        }
    }

    private void showSortDialog() {
        if (sortDialog == null) sortDialog = new SortDialog(mContext);
        sortPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivSort).hasShadowBg(false) // 去掉半透明背景
                .asCustom(sortDialog);
        sortDialog.setListener(new SortDialog.Ilistener() {

            @Override
            public void click(int position, String name) {
                sortBy = position;
                mDataBinding.tvSortType.setText(name);
                sortFileBeanList();
            }
        });
        sortPopup.show();
    }

    private void showEditDialog(View view) {
        if (editDialog == null) editDialog = new EditDialog(mContext);
        editPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Left) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(false) // 去掉半透明背景
                .asCustom(editDialog);
        editDialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickDelete() {
                showDeleteDialog();
            }

            @Override
            public void clickRename() {
                showRenameDialog();
            }

            @Override
            public void clickMove() {
                MoveActivity.sPath = mSelPath;
                startActivity(MoveActivity.class);
            }

            @Override
            public void clickCopy() {
                SPUtils.getInstance().put(Content.copy_file, mSelPath);
                ToastUtils.make().setGravity(Gravity.CENTER, 0, 0).show(R.string.copy_tip);
            }
        });
        editPopup.show();
    }

    private void showDeleteDialog() {
        DeleteDialog deleteDialog = new DeleteDialog(mContext);
        deleteDialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                delete();
            }
        });
        deleteDialog.show();
    }

    private void showRenameDialog() {
        RenameDialog renameDialog = new RenameDialog(mContext);
        renameDialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(mSelPath, name + "." + FileUtils.getFileExtension(mSelPath));
                getData(mCurrentRootPath);
            }
        });
        renameDialog.show();
    }

    private void showAddDialog() {
        if (addDialog == null) addDialog = new AddDialog(mContext);
        addPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivAdd).hasShadowBg(false) // 去掉半透明背景
                .asCustom(addDialog);
        addDialog.setListener(new AddDialog.Ilistener() {
            @Override
            public void clickAddFolder() {
                showAddFolderDialog();
            }

            @Override
            public void clickAddText() {
                showAddTextDialog();
            }

            @Override
            public void clickSystemFile() {
                mCurrentRootPath = Environment.getExternalStorageDirectory().getPath();
                getData(mCurrentRootPath);
            }

            @Override
            public void clickImportPicture() {
                StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                        .reqPermissionDesc(getString(R.string.get_picture_permission))
                        .callback(new StkPermissionHelper.ACallback() {
                            @Override
                            public void onGranted() {
                                PhotoSelectorBuilder
                                        .builder(LocalFileActivity.this)
                                        .mode(PhotoConfig.Mode.PHOTO)
                                        .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                                            @Override
                                            public void onResult(List<SelectMediaEntity> data) {
                                                for (int i = 0, size = data.size(); i < size; i++) {
                                                    SelectMediaEntity entity = data.get(i);
                                                    FileUtils.copy(entity.getPath(), mCurrentRootPath + File.separator
                                                            + FileUtils.getFileName(entity.getPath()));
                                                    getData(mCurrentRootPath);
                                                }
                                            }
                                        });
                            }
                        }).request();
            }

            @Override
            public void clickPaste() {
                if (TextUtils.isEmpty(SPUtils.getInstance().getString(Content.copy_file))) {
                    ToastUtils.showShort(getString(R.string.please_copy_file));
                } else {
                    copy();
                }
            }
        });
        addPopup.show();
    }

    private void showAddFolderDialog() {
        AddFolderDialog addFolderDialog = new AddFolderDialog(mContext);
        addFolderDialog.setListener(new AddFolderDialog.Ilistener() {
            @Override
            public void clickAddFolder(String name) {
                addFolder(name);
            }
        });
        addFolderDialog.show();
    }

    private void showAddTextDialog() {
        AddTextDialog addTextDialog = new AddTextDialog(mContext);
        addTextDialog.setListener(new AddTextDialog.Ilistener() {
            @Override
            public void clickAddText(String name) {
                addText(name);
            }
        });
        addTextDialog.show();
    }

    private void sortFileBeanList() {
        switch (sortBy) {
            case 0:
                fileAdapter.setList(mFileBeanList);
                if (isOrder) {
                    Collections.reverse(fileAdapter.getData());
                }
                break;
            case 1:
                // 按名称排序
                if (isOrder) {
                    Collections.sort(fileAdapter.getData(), (f1, f2) -> f1.getName().compareToIgnoreCase(f2.getName()));
                } else {
                    Collections.sort(fileAdapter.getData(), (f1, f2) -> f2.getName().compareToIgnoreCase(f1.getName()));
                }
                break;
            case 2:
                // 按时间排序
                if (isOrder) {
                    Collections.sort(fileAdapter.getData(), (f1, f2) -> Long.compare(f1.getDateModified(), f2.getDateModified()));
                } else {
                    Collections.sort(fileAdapter.getData(), (f1, f2) -> Long.compare(f2.getDateModified(), f1.getDateModified()));
                }
                break;
            case 3:
            case 4:
                // 按文件大小排序
                // 按类型排序
                if (isOrder) {
                    Collections.sort(fileAdapter.getData(), (f1, f2) -> Long.compare(f1.getSize(), f2.getSize()));
                } else {
                    Collections.sort(fileAdapter.getData(), (f1, f2) -> Long.compare(f2.getSize(), f1.getSize()));
                }
                break;
            default:
                break;
        }
        fileAdapter.notifyDataSetChanged();
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileUtils.delete(mSelPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData(mCurrentRootPath);
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void addFolder(String name) {
        File file = new File(mCurrentRootPath, name);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (mkdirs) {
                ToastUtils.showShort(R.string.add_dir_s);
                getData(mCurrentRootPath);
            } else {
                ToastUtils.showShort(R.string.add_dir_s);
            }
        } else {
            ToastUtils.showShort(R.string.is_dir);
        }
    }

    private void addText(String name) {
        File file = new File(mCurrentRootPath, File.separator + name + ".txt");
        if (!file.exists()) {
            boolean newFile = false;
            try {
                newFile = file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (newFile) {
                ToastUtils.showShort(R.string.add_file_s);
                getData(mCurrentRootPath);
            } else {
                ToastUtils.showShort(R.string.add_file_f);
            }
        } else {
            ToastUtils.showShort(R.string.is_file);
        }
    }

    private void copy() {
        File sourceFile = new File(SPUtils.getInstance().getString(Content.copy_file));
        File destinationFolder = new File(mCurrentRootPath);
        // 如果目标文件夹不存在，则创建它
        if (!destinationFolder.exists()) {
            destinationFolder.mkdirs();
        }
        // 构造目标文件路径
        File destinationFile = new File(destinationFolder.getPath() + File.separator + sourceFile.getName());
        FileUtils.copy(sourceFile, destinationFile);
        ToastUtils.showShort(R.string.copy_suc);
        SPUtils.getInstance().remove(Content.copy_file);
        getData(mCurrentRootPath);
    }

    //跳转到预览文档应用
    private void gotoPreviewDoc(Uri selUri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setType("application/pdf"); // 设置要打开的文档类型（PDF格式）
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            // 设备上至少安装了一个支持打开PDF文档的应用程序
            Intent intent2 = new Intent(Intent.ACTION_VIEW);
            intent2.setData(selUri);
            startActivity(intent2);
        } else {
            // 设备上没有安装任何支持打开PDF文档的应用程序
            ToastUtils.showShort(R.string.no_preview_app);
        }
    }

}